/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CommandHistoryBox.java
 *
 * Created on 12-apr-2010, 20:47:28
 */
package nl.lemval.nododue.dialog;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

import nl.lemval.nododue.cmd.CommandHistory;
import nl.lemval.nododue.util.HistoryElem;
import org.jdesktop.application.Action;

/**
 *
 * @author Michael
 */
public class CommandHistoryBox extends javax.swing.JDialog {

    private CommandHistory historyData;
    private DefaultListModel historyModel;
    private Timer timer;

    /** Creates new form CommandHistoryBox */
    public CommandHistoryBox(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        historyModel = new DefaultListModel();
        initComponents();
        getRootPane().setDefaultButton(close);
        KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        getRootPane().registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
        stroke = KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK);
        getRootPane().registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        historyList.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent me) {
                if (SwingUtilities.isRightMouseButton(me)) {
                    updateMenu.show(historyList, me.getX(), me.getY());
                }
            }
        });

        historyList.addMouseMotionListener(new MouseMotionListener() {
            public void mouseDragged(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    Rectangle rect = historyList.getVisibleRect();
                    if ( rect.contains(e.getPoint()) ) {
                        updateMenu.show(historyList, e.getX(), e.getY());
                    } else {
                        updateMenu.setVisible(false);
                    }
                }
            }
            public void mouseMoved(MouseEvent e) {
            }
        });
        autoUpdate();
    }

    public void setHistory(CommandHistory data) {
        this.historyData = data;
    }

    @Override
    public void setVisible(boolean b) {
        updateData();
        super.setVisible(b);
    }

    private void updateData() {
        if (historyData != null) {
            ArrayList<HistoryElem> cmds = historyData.getCommands();
            historyModel.clear();
            for (HistoryElem historyElem : cmds) {
                historyModel.addElement(historyElem);
            }
        }
        int lastIndex = historyModel.getSize() - 1;
        if (lastIndex >= 0) {
             historyList.ensureIndexIsVisible(lastIndex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        updateMenu = new javax.swing.JPopupMenu();
        clearScreenItem = new javax.swing.JMenuItem();
        updateItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        removeSelectedItem = new javax.swing.JMenuItem();
        removeAllItem = new javax.swing.JMenuItem();
        title = new javax.swing.JLabel();
        close = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        historyList = new javax.swing.JList();
        autoUpdate = new javax.swing.JCheckBox();

        updateMenu.setName("updateMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(nl.lemval.nododue.NodoDueManager.class).getContext().getActionMap(CommandHistoryBox.class, this);
        clearScreenItem.setAction(actionMap.get("clearScreen")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(nl.lemval.nododue.NodoDueManager.class).getContext().getResourceMap(CommandHistoryBox.class);
        clearScreenItem.setText(resourceMap.getString("clearScreenItem.text")); // NOI18N
        clearScreenItem.setName("clearScreenItem"); // NOI18N
        updateMenu.add(clearScreenItem);

        updateItem.setAction(actionMap.get("updateScreen")); // NOI18N
        updateItem.setText(resourceMap.getString("updateItem.text")); // NOI18N
        updateItem.setName("updateItem"); // NOI18N
        updateMenu.add(updateItem);

        jSeparator1.setName("jSeparator1"); // NOI18N
        updateMenu.add(jSeparator1);

        removeSelectedItem.setAction(actionMap.get("removeSelectedItems")); // NOI18N
        removeSelectedItem.setText(resourceMap.getString("removeSelectedItem.text")); // NOI18N
        removeSelectedItem.setName("removeSelectedItem"); // NOI18N
        updateMenu.add(removeSelectedItem);

        removeAllItem.setAction(actionMap.get("removeAllItems")); // NOI18N
        removeAllItem.setText(resourceMap.getString("removeAllItem.text")); // NOI18N
        removeAllItem.setName("removeAllItem"); // NOI18N
        updateMenu.add(removeAllItem);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(resourceMap.getString("title.text")); // NOI18N
        setName("Form"); // NOI18N

        title.setFont(title.getFont().deriveFont(title.getFont().getStyle() | java.awt.Font.BOLD));
        title.setText(resourceMap.getString("title.text")); // NOI18N
        title.setName("title"); // NOI18N

        close.setAction(actionMap.get("closeBox")); // NOI18N
        close.setText(resourceMap.getString("close.text")); // NOI18N
        close.setName("close"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        historyList.setModel(historyModel);
        historyList.setName("historyList"); // NOI18N
        historyList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                mousePressedInHistoryList(evt);
            }
        });
        jScrollPane1.setViewportView(historyList);

        autoUpdate.setAction(actionMap.get("autoUpdate")); // NOI18N
        autoUpdate.setSelected(true);
        autoUpdate.setText(resourceMap.getString("autoUpdate.text")); // NOI18N
        autoUpdate.setName("autoUpdate"); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                    .add(title)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(autoUpdate)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 81, Short.MAX_VALUE)
                        .add(close)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(title)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(close)
                    .add(autoUpdate))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mousePressedInHistoryList(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mousePressedInHistoryList
        if ( evt.isAltDown() && evt.getButton() == MouseEvent.BUTTON1 ) {
            dump();
        }
    }//GEN-LAST:event_mousePressedInHistoryList

    @Action
    public void closeBox() {
        dispose();
    }

    @Action
    public void removeSelectedItems() {
        Object[] cmds = historyList.getSelectedValues();
        for (int i = 0; i < cmds.length; i++) {
            historyData.removeCommand((HistoryElem) cmds[i]);
        }
        updateData();
    }

    @Action
    public void removeAllItems() {
        int size = historyList.getModel().getSize();
        for (int i = 0; i < size; i++) {
            historyData.removeCommand((HistoryElem) historyList.getModel().getElementAt(i));
        }
        updateData();
    }

    @Action
    public void clearScreen() {
        historyModel.clear();
    }

    @Action
    public void updateScreen() {
        updateData();
    }

    @Action
    final public void autoUpdate() {
        if ( timer == null ) {
            timer = new Timer(2500, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    updateData();
                }
            });
            timer.setRepeats(true);
        }
        if ( autoUpdate.isSelected() ) {
            timer.start();
        } else {
            timer.stop();
        }
    }

    @Action
    public void dump() {
        ArrayList<HistoryElem> cmds = historyData.getCommands();
        for (HistoryElem historyElem : cmds) {
            System.out.println(historyElem);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox autoUpdate;
    private javax.swing.JMenuItem clearScreenItem;
    private javax.swing.JButton close;
    private javax.swing.JList historyList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JMenuItem removeAllItem;
    private javax.swing.JMenuItem removeSelectedItem;
    private javax.swing.JLabel title;
    private javax.swing.JMenuItem updateItem;
    private javax.swing.JPopupMenu updateMenu;
    // End of variables declaration//GEN-END:variables
}
